package cate.game.client.interceptor;

import cate.common.annotation.OperationSetter;
import cate.game.GameBody;
import cate.game.client.ClientContext;
import cate.game.client.msg.MsgInput;
import cate.game.log.GameLoggerFactory;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;

import java.lang.reflect.Field;

public class OperationAdderInterceptor extends AbstractCommandInterceptor{
    @Override
    public void execute(MsgInput msgInput, GameBody gameBody, ClientContext clientContext) {
        OperationSetter setter = msgInput.getClass().getAnnotation(OperationSetter.class);
        if(setter != null){
            if(clientContext.getRole() == null){
                Logger logger = GameLoggerFactory.getLogger(gameBody, OperationAdderInterceptor.class);
                logger.error("cc.getRole为空，msg class={}", msgInput.getClass().getName());
                return;
            }
            clientContext.getRole().log.setOperation(setter.value());
            if(StringUtils.isNotBlank(setter.sub())){
                Field field;
                try{
                    field = msgInput.getClass().getField(setter.sub());
                    clientContext.getRole().log.setOperationSub((int) field.get(msgInput));
                }catch(Exception e){
                    //没这属性就拉倒
                }
            }
        }
        try {
            next.execute(msgInput, gameBody, clientContext);
        } catch (Exception e) {
            Logger logger = GameLoggerFactory.getLogger(gameBody, OperationAdderInterceptor.class);
            logger.error("Caught optimistic locking exception: ", e);
        } finally {
            if(clientContext.getRole() != null){
                clientContext.getRole().log.clearOperation();
            }
        }
    }
}
